package per.srp.demo.web.controller.utils;

import per.srp.demo.carLink.entity.CarCommand;

import java.util.regex.Pattern;

public class CommandStringTool {

    public static final String blank = "[\\s\\n\\r]*";
    public static final String blank2 = "[\\s\\n\\r]+";
    public static final String commands = "(forcebreak)|(up)|(down)|(left)|(right)|(stop)";
    public static final String commandRegx = blank+"("+commands+")"+blank+"(\\("+blank+"[\\d]+"+blank+"\\,"+blank+"[\\d]+"+blank+"\\)"+blank+";)";

    public static final Pattern commandPattern = Pattern.compile(commandRegx);

    /**
     * 检查命令格式
     * @param stringFromClient
     * @return
     */
    public static String getWrongPart(String stringFromClient){
        String inputTemp = stringFromClient.replaceAll(blank2,"");
        inputTemp = inputTemp.replaceAll(commandRegx,"");
        return "".equals(inputTemp)?null:inputTemp;
    }

    public static CarCommand[] StringToCommands(String commandString){
        commandString = commandString.replaceAll(blank2,"");
        String[] commandsStringArray = commandString.split(";");

//        left(10,20);
        CarCommand[] result = new CarCommand[commandsStringArray.length];
        int i=0;
        for(String eachCommandString : commandsStringArray){
            int part1 = eachCommandString.indexOf("(");
            int part2 = eachCommandString.indexOf(",");
            int part3 = eachCommandString.indexOf(")");
            String command = eachCommandString.substring(0,part1);
            String time = eachCommandString.substring(part1+1,part2);
            String v = eachCommandString.substring(part2+1,part3);
            result[i] = new CarCommand(command,Integer.valueOf(time),v);
            i++;
        }
        return result;
    }
}
